/*
 * @: redux 不需要依赖react
 * @version: 1.0
 * @Author: ziwei
 * @Date: 2021-10-18 17:38:14
 * @LastEditors: ziwei
 * @LastEditTime: 2021-11-02 15:44:28
 */
function isPlainObject(obj) {
  if(typeof obj !== 'object'||Object === null){
    return false
  }
  //let obj = {};let obj2 = new Object;obj2.__pro__ = Object.prototype
  return Object.getPrototypeOf(obj)===Object.prototype
}

//创建仓库
//reducer 处理器
//preloadedState 默认状体啊 或者说初始状态
function createStore(reducer, preloadedState) {
    let state = preloadedState; //闭包变量
    let listeners = []

    function getState() {
        return state
    }

    function dispatch(action) {
      if(!isPlainObject(action)){
        throw new Error('action 必须是纯对象，不能是函数或者其它的');
      }
        //根据老动作和action,计算新状态
        state = reducer(state, action)
        //if(listeners.type==action.type){} 类型一样才执行 可以进行优化
        listeners.forEach(l => l());
        return action
    }

    function subscribe(listener) {
        listeners.push(listener)
        //subscribe 会返回一个取消订阅的函数
        return ()=>{
            listeners = listeners.filter(l=>l!==listener)
        }
    }
    dispatch({type:'@@REDUX/INIT'})
    return {
        getState, //用来获取当前的仓库的状态
        dispatch, //向仓库派发动作
        subscribe, //用来订阅仓库中状态的变化
    }
}

export default createStore